<template>
  <div class="container">
    <div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="姓名：">
              <el-input
                v-model="person.name"
                placeholder="姓名"
                style="width: 200px"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="所属机构：">
              <el-select v-model="person.client" placeholder filterable>
                <el-option
                  v-for="item in person.clientList"
                  :key="item.CLIENT_NO"
                  :label="item.CLIENT_NAME"
                  :value="item.CLIENT_NO"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form ref="form" :model="form" style="float: left">
            <el-button size="mini" type="primary" @click="personQuery"
              >查 询</el-button
            >
            <el-button size="mini" type="success" @click="handleAdd"
              >新 增</el-button
            >

          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
      highlight-current-row
      border
    >
      <el-table-column
        prop="NAME1"
        label="类型名称"
        align="center"
      ></el-table-column>
      <el-table-column prop="NAME2" label="考核周期" align="center"></el-table-column>
      <!-- <el-table-column prop="NAME3" label="检查频次" align="center"></el-table-column> -->
      <el-table-column prop="NAME4" label="分值占比" align="center"></el-table-column>

      
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 新增人员 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="show"
      width="45%"
      :modal="false"
    >
      <el-form
        ref="newPersonForm"
        :model="newPersonForm"
        label-width="120px"
        class="flex"
      >
        <el-form-item prop="NAME" label="姓名" class="wid50">
          <el-input style="width: 207px;"
            v-model="newPersonForm.NAME"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="MOBILEPHONE" label="电话号码" class="wid50">
          <el-input style="width: 207px;"
            v-model="newPersonForm.MOBILEPHONE"
            placeholder="请输入电话"
            maxlength="11"
            oninput="value=value.replace(/[^\d]/g,'')"
          ></el-input>
        </el-form-item>

        <el-form-item prop="SEX" label="性别" class="wid50">
          <el-radio v-model="newPersonForm.SEX" label="男">男</el-radio>
          <el-radio v-model="newPersonForm.SEX" label="女">女</el-radio>
        </el-form-item>
        <el-form-item prop="DRIVINGYEAR" label="年龄" class="wid50">
          <el-input style="width: 207px;"
            v-model="newPersonForm.DRIVINGYEAR"
            placeholder="请输入年龄"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item prop="SIMCARD_NO" label="通讯卡号" class="wid50">
          <el-input v-model="newPersonForm.SIMCARD_NO" placeholder="请输入通讯卡号" :disabled="addDialogTitle != '新增人员信息'"></el-input>
        </el-form-item> -->
        <el-form-item prop="CLIENT_NO" label="所属机构" class="wid50">
          <el-select v-model="newPersonForm.CLIENT_NO" placeholder="请选择所属机构">
            <el-option
              v-for="item in person.clientList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="CLIENT_NO" label="所属小组" class="wid50">
          <el-select v-model="newPersonForm.CLIENT_NO" placeholder="请选择所属小组">
            <el-option
              v-for="item in person.clientList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            />
          </el-select>
        </el-form-item>


        <el-form-item prop="CLIENT_NO" label="考评设备类型" class="wid50">
          <el-select v-model="newPersonForm.CLIENT_NO" placeholder="请选择考评设备类型">
            <el-option
              v-for="item in person.clientList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="CLIENT_NO" label="负责区域" class="wid50">
          <el-select v-model="newPersonForm.CLIENT_NO" placeholder="请选择负责区域">
            <el-option
              v-for="item in person.clientList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="CLIENT_NO" label="负责考核来源" class="wid50">
          <el-select v-model="newPersonForm.CLIENT_NO" placeholder="请选择负责考核来源">
            <el-option
              v-for="item in person.clientList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="CLIENT_NO" label="负责考核类型" class="wid50">
          <el-select v-model="newPersonForm.CLIENT_NO" placeholder="请选择负责考核类型">
            <el-option
              v-for="item in person.clientList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="CLIENT_NO" label="负责考核项目" class="wid50">
          <el-select v-model="newPersonForm.CLIENT_NO" placeholder="请选择负责考核项目">
            <el-option
              v-for="item in person.clientList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="CLIENT_NO" label="工作时间" class="wid50">
          <el-select v-model="newPersonForm.CLIENT_NO" placeholder="请选择工作时间">
            <el-option
              v-for="item in person.clientList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            />
          </el-select>
        </el-form-item>

        
      </el-form>
      <!-- </div> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/css/common.css'
import { formatDate } from '@/common/js/date.js'
import export2Excel from '@/utils/exportExcel/index.js'
export default {
  data () {
    return {
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      // 人员管理
      person: {
        name: '',
        client: localStorage.getItem('CLIENT_NO'),
        clientList: []
      },
      show: false,
      // 新增人员
      newPersonForm: {
        VID: '',
        NAME: '',
        MOBILEPHONE: '',
        SIMCARD_NO: '',
        BIRTHDAY: '',
        WORKDATE: '',
        SEX: '男',
        WORKTYPE: '',
        CLIENT_NO: '',
        WORKCARTYPE: '',
        arrWORKCARTYPE:[],
      },
      tableData: [],
      originalData: [],
      CarTypeData: [],
    }
  },
  created () {
    this.getTeamList();
    this.getlistdata();
    this.getCarTypedata();
  },
  methods: {
    async getTeamList () {
      var url = 'Vehicle/GetGroupList?ClientNo=' + localStorage.getItem('CLIENT_NO') // zxdata
      let { data } = await this.$Http.get(url)
      this.person.clientList = data
      // this.attendanceMonth.records.teamList = data
    },
    async getlistdata () {
      // var url = 'Vehicle/GetDriverInfoPB?ClientNo=' + this.person.client + '&NAME=' + this.person.name
      // const { data } = await this.$Http.get(url)
      // 类型名称、考核周期、检查频次、分值占比。
      // 日常检查、抽查考核、集中评比、被动接收
      this.originalData = [
      {"NAME1":"日常检查","NAME2":"1周","NAME3":"每周","NAME4":"35%"},
      {"NAME1":"抽查考核","NAME2":"不定期","NAME3":"每周","NAME4":"20%"},
      {"NAME1":"集中评比","NAME2":"1月","NAME3":"每周","NAME4":"20%"},
      {"NAME1":"被动接收","NAME2":"不定期","NAME3":"每周","NAME4":"25%"},]
      // data.forEach(element => {
      //   element.birthday = formatDate(new Date(element.BIRTHDAY), 'yyyy-MM-dd')
      //   element.workdate = formatDate(new Date(element.WORKDATE), 'yyyy-MM-dd')
      //   this.originalData.push(element)
      // });
      this.personQuery()
    },
    // 车辆类型
    async getCarTypedata () {
      var url = 'Vehicle/GetCarTypeInfoPB?ClientNo=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      this.CarTypeData = data
    },
    // 人员管理查询
    personQuery () {
      this.currentPage = 1;
      this.tableData = this.originalData
      // const { name, client } = this.person
      // if (name) this.tableData = this.tableData.filter(item => item.NAME.includes(name))
      // if (client) this.tableData = this.tableData.filter(item => client === item.CLIENT_NO)
    },

    // 打开新增窗口
    handleAdd () {
      this.addDialogTitle = '新增人员信息'
      //清空编辑框
      this.newPersonForm = {}
      //展示窗口
      this.show = true;
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      this.newPersonForm = Object.assign({}, row);
      this.addDialogTitle = '编辑人员信息'
      this.show = true;
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {

      if (this.newPersonForm.NAME == null ) {
        this.$message.warning(`姓名不得为空`);
      } else {
        if (this.addDialogTitle == '新增人员信息') {
          this.addPerson()
        } else {
          this.saveEdit()
        }
      }
    },
    async addPerson () {
      var str = '';
      console.log(this.newPersonForm.arrWORKCARTYPE)
      this.newPersonForm.arrWORKCARTYPE.forEach(element => {
        str = str + element + ','
      });
      str = str.substring(0, str.length - 1);
      this.newPersonForm.WORKCARTYPE = str
      this.$axios({
        url: 'Vehicle/SaveDriverInfoPB',
        method: 'post',
        data: {
          DRIVERID: '-1',
          NAME: this.newPersonForm.NAME,
          CLIENT_NO: this.newPersonForm.CLIENT_NO,
          SEX: this.newPersonForm.SEX,
          MOBILEPHONE: this.newPersonForm.MOBILEPHONE,
          BRITHDAY: this.newPersonForm.BRITHDAY,
          WORKTIME: this.newPersonForm.WORKTIME,
          DRIVINGYEAR: this.newPersonForm.DRIVINGYEAR,
          DRIVERCARDNUMBER: this.newPersonForm.DRIVERCARDNUMBER,
          DRIVERCARDTYPE: this.newPersonForm.DRIVERCARDTYPE,
          ALLOWCARTYPE: this.newPersonForm.ALLOWCARTYPE,
          WORKCARTYPE: this.newPersonForm.WORKCARTYPE,
          BLOODTYPE: this.newPersonForm.BLOODTYPE,
          DRIVERCARDSTARTTIME: this.newPersonForm.DRIVERCARDSTARTTIME,
          DRIVERCARDALLOWTIME: this.newPersonForm.DRIVERCARDALLOWTIME,
        },

      }).then((res) => {
        console.log(this.data)
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('新增成功');
          this.getlistdata()
          this.resetForm('newPersonForm')
          this.show = false
        } else {
          this.$message.error('新增失败');
        }
      })
    },
    async saveEdit () {
      var str = '';
      console.log(this.newPersonForm.arrWORKCARTYPE)
      this.newPersonForm.arrWORKCARTYPE.forEach(element => {
        str = str + element + ','
      });
      str = str.substring(0, str.length - 1);
      this.newPersonForm.WORKCARTYPE = str
      this.$axios({
        url: 'Vehicle/SaveDriverInfoPB',
        method: 'post',
        data: {
          DRIVERID: this.newPersonForm.DRIVERID,
          NAME: this.newPersonForm.NAME,
          CLIENT_NO: this.newPersonForm.CLIENT_NO,
          SEX: this.newPersonForm.SEX,
          MOBILEPHONE: this.newPersonForm.MOBILEPHONE,
          BRITHDAY: this.newPersonForm.BRITHDAY,
          WORKTIME: this.newPersonForm.WORKTIME,
          DRIVINGYEAR: this.newPersonForm.DRIVINGYEAR,
          DRIVERCARDNUMBER: this.newPersonForm.DRIVERCARDNUMBER,
          DRIVERCARDTYPE: this.newPersonForm.DRIVERCARDTYPE,
          ALLOWCARTYPE: this.newPersonForm.ALLOWCARTYPE,
          WORKCARTYPE: this.newPersonForm.WORKCARTYPE,
          BLOODTYPE: this.newPersonForm.BLOODTYPE,
          DRIVERCARDSTARTTIME: this.newPersonForm.DRIVERCARDSTARTTIME,
          DRIVERCARDALLOWTIME: this.newPersonForm.DRIVERCARDALLOWTIME,
        },

      }).then((res) => {
        console.log(this.data)
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('编辑成功');
          this.getlistdata()
          this.resetForm('newPersonForm')
          this.show = false
        } else {
          this.$message.error('编辑失败');
        }
      })
      const params = {
        VID: this.newPersonForm.VID,
        Name: this.newPersonForm.NAME,
        SimCardNo: this.newPersonForm.SIMCARD_NO,
        Sex: this.newPersonForm.SEX,
        ClientNo: this.newPersonForm.CLIENT_NO,
        MOBILEPHONE: this.newPersonForm.MOBILEPHONE,
        WorkType: this.newPersonForm.WORKTYPE,
        BirhDay: this.newPersonForm.BIRTHDAY,
        WorkDate: this.newPersonForm.WORKDATE
      }
    },
    // 重置新增人员表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
      // this.newPersonForm.SIMCARD_NO = ''
      // this.newPersonForm.BIRTHDAY = ''
      // this.newPersonForm.WORKDATE = ''
      this.newPersonForm = {
        show: true,
        NAME: '',
        MOBILEPHONE: '',
        SIMCARD_NO: '',
        BIRTHDAY: '',
        WORKDATE: '',
        SEX: '男',
        WORKTYPE: '',
        CLIENT_NO: ''
      }
    },
    // 删除
    async handleDelete (index, row) {
      const confirmResult = await this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult == 'confirm') {
        const params = {
          DriverID: row.DriverID,
        }
        const { data } = await this.$Http.get('Vehicle/DeleteDriverInfoPB', { params })
        if (data.IsSucess) {
          this.$message.success('删除成功')
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('删除失败');
        }
      } else {
        this.$message.info('取消删除')
        this.isVisibleEdit = false
      }

    },
    // 导入Excel
    onChange (file, fileList) {
      //  console.log(fileList);
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      let that = this;
      const files = that.fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: "binary"// 以字符编码的方式解析
          });

          if (workbook.SheetNames.length >= 1) {
            //  this.$message({
            //    message: "导入数据表格成功",
            //    showClose: true,
            //    type: "success"
            //  });

            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            console.log(ws)
            this.inputExcelDataLength = ws.length
            this.fullscreenLoading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            for (let i = 0, len = ws.length; i < len; i++) {
              var item = ws[i]
              //   var sheetData = {
              //     VID: item['居民电话'],
              //     RUBBISH_NAME: item["垃圾品名"],
              //     WEIGHT: item["垃圾称重"],
              //     photo: '',
              //     LONGITUDE: 0,
              //     LATITUDE: 0
              //   }
              //   let exceldata =  []
              //   exceldata.push(sheetData)
              this.addWeight(item)
            }
          } else {
            this.$message.error("未读取到表格内容");
          }
        } catch (e) {
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },
    async addWeight (item) {
      this.$axios({
        url: 'Vehicle/AddWorkerApi',
        method: 'post',
        data: {
          VID: item['人员ID'],
          Name: item['姓名'],
          SimCardNo: item['通讯卡号'],
          ClientNo: item['班组编号'],
          Sex: item['性别'],
          MOBILEPHONE: item['电话'],
          WorkType: item['工种'],
          // BirhDay: item['出生日期'],
          workdate: item['入职时间'],
        }
      }).then(res => {
        console.log(res)
        this.inputExcelDataIndex++

        if (res.data.IsSucess) {
          this.fullscreenLoading.close()
          this.$message.success('表格文件导入成功')
          this.getlistdata()
        } else {
          this.fullscreenLoading.close()
          this.$message.error('表格文件导入失败' + '，' + res.data.Message);

        }
        if (this.inputExcelDataIndex == this.inputExcelDataLength) {
          this.fullscreenLoading.close()
          if (this.strError.length == 0) {
            this.$message.success('表格文件导入成功')
            this.getlistdata()
          } else {
            // this.$message.error('表格文件导入结束<br/>' + this.strError);
            this.$message({
              message: '表格文件导入结束，' + this.strError,
              type: 'error',
              duration: 5000
            })
          }
          this.getlistdata()
        }
      })
      //   })
    },
    // 导出Excel
    exportExcel () {
      let excelName = '人员信息记录'
      const tHeader = ['人员ID', '姓名', '通讯卡号', '班组编号', '性别', '电话', '工种', '入职时间']
      const filterVal = ['VID', 'NAME', 'SIMCARD_NO', 'CLIENT_NO', 'SEX', 'MOBILEPHONE', 'WORKTYPE', 'workdate']
      export2Excel(tHeader, filterVal, this.tableData, excelName)
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getData();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    }
  }
}
</script>
<style scoped lang='less'>
.content {
  overflow-y: scroll;
}
</style>